package main

import (
	"fmt"
	"sync"
	"time"
)

// 读写互斥锁（读 > 写的场景）
var (
	Num    = 0
	wg     sync.WaitGroup
	lock   sync.Mutex   // 互斥锁
	rwLock sync.RWMutex // 读写互斥锁
)

func write(x int) {
	defer wg.Done()
	// 加锁
	// lock.Lock()
	rwLock.Lock()
	Num += x
	time.Sleep(3 * time.Millisecond)
	// 释放锁
	// lock.Unlock()
	rwLock.Unlock()
}
func rend() {
	defer wg.Done()
	// 加锁
	// lock.Lock()
	rwLock.RLock()
	fmt.Printf("Num: %v\n", Num)
	time.Sleep(time.Millisecond)
	// 释放锁
	// lock.Unlock()
	rwLock.RUnlock()
}

func main() {
	startNow := time.Now()
	for i := 0; i < 10; i++ {
		go write(10)
		wg.Add(1)
	}
	time.Sleep(time.Second)
	for i := 0; i < 1000; i++ {
		go rend()
		wg.Add(1)
	}
	wg.Wait()
	fmt.Println(time.Now().Sub(startNow))
}
